<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>浅谈styled-components | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,react,">
  

  <meta name="description" content="一、简介 styled components一种全新的控制样式的编程方式，它能解决CSS全局作用域的问题，而且移除了样式和组件间的映射关系   我们要理清一件事情：styled-components 只是 CSS 层面的高度抽象。它只是解析定义在 JavaScript中的 CSS，然后生成对应 CSS 的 JSX元素  import React from &apos;react&apos;;import styled">
<meta name="keywords" content="JavaScript,react">
<meta property="og:type" content="article">
<meta property="og:title" content="浅谈styled-components">
<meta property="og:url" content="http://blog.poetries.top/2017/11/08/react-styled-components/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、简介 styled components一种全新的控制样式的编程方式，它能解决CSS全局作用域的问题，而且移除了样式和组件间的映射关系   我们要理清一件事情：styled-components 只是 CSS 层面的高度抽象。它只是解析定义在 JavaScript中的 CSS，然后生成对应 CSS 的 JSX元素  import React from &apos;react&apos;;import styled">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/469.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.934Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浅谈styled-components">
<meta name="twitter:description" content="一、简介 styled components一种全新的控制样式的编程方式，它能解决CSS全局作用域的问题，而且移除了样式和组件间的映射关系   我们要理清一件事情：styled-components 只是 CSS 层面的高度抽象。它只是解析定义在 JavaScript中的 CSS，然后生成对应 CSS 的 JSX元素  import React from &apos;react&apos;;import styled">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/2019/10/469.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、简介"><span class="toc-text">一、简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、基于-props-定制主题"><span class="toc-text">二、基于 props 定制主题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、组件样式继承"><span class="toc-text">三、组件样式继承</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、组件内部使用-className"><span class="toc-text">四、组件内部使用 className</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、组件中维护其他属性"><span class="toc-text">五、组件中维护其他属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、CSS-动画支持"><span class="toc-text">六、CSS 动画支持</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、兼容现在已有的-react-components-和-css-框架"><span class="toc-text">七、兼容现在已有的 react components 和 css 框架</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、实战篇"><span class="toc-text">八、实战篇</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、总结"><span class="toc-text">九、总结</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-react-styled-components" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">浅谈styled-components</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2017.11.08</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.7k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 7分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、简介"><a href="#一、简介" class="headerlink" title="一、简介"></a>一、简介</h2><blockquote>
<p><code>styled components</code>一种全新的控制样式的编程方式，它能解决<code>CSS</code>全局作用域的问题，而且移除了样式和组件间的映射关系</p>
</blockquote>
<ul>
<li>我们要理清一件事情：<code>styled-components</code> 只是 <code>CSS</code> 层面的高度抽象。它只是解析定义在 <code>JavaScript</code>中的 <code>CSS</code>，然后生成对应 <code>CSS</code> 的 <code>JSX</code>元素</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> styled <span class="keyword">from</span> <span class="string">'styled-components'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; render &#125; <span class="keyword">from</span> <span class="string">'react-dom'</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">const</span> Title = styled.h1<span class="string">`</span></span><br><span class="line"><span class="string">    font-size: 1.5em;</span></span><br><span class="line"><span class="string">    text-align: center;</span></span><br><span class="line"><span class="string">    color: palevioletred;</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"></span><br><span class="line">WrapSearchBox=styled.div<span class="string">`</span></span><br><span class="line"><span class="string">    width : 200px;</span></span><br><span class="line"><span class="string">    // 媒体查询</span></span><br><span class="line"><span class="string">    @media (max-width : 800px)&#123;</span></span><br><span class="line"><span class="string">    	width : 100%;</span></span><br><span class="line"><span class="string">    	padding-left:15px;	</span></span><br><span class="line"><span class="string">    	margin-top:-14px;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">    &gt;div&#123;</span></span><br><span class="line"><span class="string">    	@media (max-width : 800px)&#123;</span></span><br><span class="line"><span class="string">    		width : 100%  !important;</span></span><br><span class="line"><span class="string">    	&#125;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">    &gt;div&gt;input &#123;</span></span><br><span class="line"><span class="string">    	width:200px !important;</span></span><br><span class="line"><span class="string">    	padding-left:25px !important;</span></span><br><span class="line"><span class="string">    	@media (max-width : 800px)&#123;</span></span><br><span class="line"><span class="string">    		width : 100%  !important;</span></span><br><span class="line"><span class="string">    	&#125;</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">`</span></span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">    render() &#123;</span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            &lt;Title&gt;Hello world&lt;<span class="regexp">/Title&gt;</span></span><br><span class="line"><span class="regexp">        )</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br><span class="line"><span class="regexp"> </span></span><br><span class="line"><span class="regexp">render(</span></span><br><span class="line"><span class="regexp">    &lt;App /</span>&gt;,</span><br><span class="line">    <span class="built_in">document</span>.getElementById(<span class="string">'app'</span>)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<ul>
<li><code>styled.h1</code>是一个标签模板函数</li>
</ul>
<blockquote>
<p><code>styled.h1</code>函数返回一个<code>React Component</code>，<code>styled components</code>会为这个<code>React Component</code>添加一个<code>class</code>，该<code>class</code>的值为一个随机字符串。传给styled.h1的模板字符串参数的值实际上是CSS语法，这些CSS会附加到该<code>React Component</code>的<code>class</code>中，从而为<code>React Component</code>添加样式</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/469.png" alt></p>
<h2 id="二、基于-props-定制主题"><a href="#二、基于-props-定制主题" class="headerlink" title="二、基于 props 定制主题"></a>二、基于 props 定制主题</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> Button = styled.button<span class="string">`</span></span><br><span class="line"><span class="string">  background: <span class="subst">$&#123;props =&gt; props.primary ? <span class="string">'palevioletred'</span> : <span class="string">'white'</span>&#125;</span>;</span></span><br><span class="line"><span class="string">  color: <span class="subst">$&#123;props =&gt; props.primary ? <span class="string">'white'</span> : <span class="string">'palevioletred'</span>&#125;</span>;</span></span><br><span class="line"><span class="string">  font-size: 1em;</span></span><br><span class="line"><span class="string">  margin: 1em;</span></span><br><span class="line"><span class="string">  padding: 0.25em 1em;</span></span><br><span class="line"><span class="string">  border: 2px solid palevioletred;</span></span><br><span class="line"><span class="string">  border-radius: 3px;</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"></span><br><span class="line">render(</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;Button&gt;Normal&lt;<span class="regexp">/Button&gt;</span></span><br><span class="line"><span class="regexp">    &lt;Button primary&gt;Primary&lt;/</span>Button&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">);</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> StyledSlider = styled(Slider)<span class="string">`</span></span><br><span class="line"><span class="string">	<span class="subst">$&#123;props =&gt; &#123;</span></span></span><br><span class="line"><span class="string"><span class="subst">		<span class="keyword">const</span> theme = props.theme.slider;</span></span></span><br><span class="line"><span class="string"><span class="subst"></span></span></span><br><span class="line"><span class="string"><span class="subst">		<span class="keyword">return</span> css`</span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">			<span class="selector-tag">div</span><span class="selector-class">.rc-slider-track</span> &#123;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">				<span class="selector-tag">background-color</span>: </span><span class="subst">$&#123;theme.themeColor&#125;</span><span class="css">;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">			&#125;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">			<span class="selector-tag">div</span><span class="selector-class">.rc-slider-handle</span> &#123;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">				<span class="selector-tag">border</span>: 2<span class="selector-tag">px</span> <span class="selector-tag">solid</span> </span><span class="subst">$&#123;theme.themeColor&#125;</span><span class="css">;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">			&#125;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">			<span class="selector-tag">span</span><span class="selector-class">.rc-slider-dot-active</span> &#123;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">				<span class="selector-tag">border-color</span>: </span><span class="subst">$&#123;theme.themeColor&#125;</span><span class="css">;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">			&#125;</span></span></span></span><br><span class="line"><span class="string"><span class="subst"><span class="css">		`</span>;</span></span></span><br><span class="line"><span class="string"><span class="subst">	&#125;</span>&#125;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> SmallSelectWrapper = styled.div <span class="string">`</span></span><br><span class="line"><span class="string">  </span></span><br><span class="line"><span class="string">  // div下面的类样式</span></span><br><span class="line"><span class="string">  .Select-control &#123;</span></span><br><span class="line"><span class="string">    height: 30px;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  .Select-input &#123;</span></span><br><span class="line"><span class="string">    height: 28px;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  .Select-value,</span></span><br><span class="line"><span class="string">  .Select-placeholder &#123;</span></span><br><span class="line"><span class="string">    line-height: 28px !important;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  .Select-menu-outer &#123;</span></span><br><span class="line"><span class="string">    max-height: 270px;</span></span><br><span class="line"><span class="string">    .Select-option.is-disabled &#123;</span></span><br><span class="line"><span class="string">      cursor: default;</span></span><br><span class="line"><span class="string">      padding-left: .5em;</span></span><br><span class="line"><span class="string">      font-weight: bold;</span></span><br><span class="line"><span class="string">      color: #333;</span></span><br><span class="line"><span class="string">      background: #f8f8f8;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  .Select-menu &#123;</span></span><br><span class="line"><span class="string">    max-height:268px;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  text-align: left;</span></span><br><span class="line"><span class="string">`</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>我们在组件中传入的所有 <code>props</code> 都可以在定义组件时获取到，这样就可以很容易实现组件主题的定制。如果没有 <code>styled-components</code>的情况下，需要使用组件 <code>style</code> 属性或者定义多个 <code>class</code> 的方式来实现</p>
</blockquote>
<h2 id="三、组件样式继承"><a href="#三、组件样式继承" class="headerlink" title="三、组件样式继承"></a>三、组件样式继承</h2><blockquote>
<p>通常在 <code>css</code> 中一般会通过给 <code>class</code>传入多个 <code>name</code> 通过空格分隔的方式来复用 <code>class</code> 定义，类似 <code>class=&quot;button tomato&quot;</code>。在 <code>styled-components</code>中利用了 <code>js</code> 的继承实现了这种样式的复用：</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> Button = styled.button<span class="string">`</span></span><br><span class="line"><span class="string">  color: palevioletred;</span></span><br><span class="line"><span class="string">  font-size: 1em;</span></span><br><span class="line"><span class="string">  margin: 1em;</span></span><br><span class="line"><span class="string">  padding: 0.25em 1em;</span></span><br><span class="line"><span class="string">  border: 2px solid palevioletred;</span></span><br><span class="line"><span class="string">  border-radius: 3px;</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> TomatoButton = Button.extend<span class="string">`</span></span><br><span class="line"><span class="string">  color: tomato;</span></span><br><span class="line"><span class="string">  border-color: tomato;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>子组件中的属性会覆盖父组件中同名的属性</p>
</blockquote>
<h2 id="四、组件内部使用-className"><a href="#四、组件内部使用-className" class="headerlink" title="四、组件内部使用 className"></a>四、组件内部使用 className</h2><blockquote>
<p>在日常开发中总会出现覆盖组件内部样式的需求，你可能想在 <code>styled-components</code> 中使用 <code>className</code>，或者在使用第三方组件时。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;Wrapper&gt;</span><br><span class="line">  &lt;h4&gt;Hello Word&lt;<span class="regexp">/h4&gt;</span></span><br><span class="line"><span class="regexp">  &lt;div className="detail"&gt;&lt;/</span>div&gt;</span><br><span class="line">&lt;<span class="regexp">/Wrapper&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="五、组件中维护其他属性"><a href="#五、组件中维护其他属性" class="headerlink" title="五、组件中维护其他属性"></a>五、组件中维护其他属性</h2><blockquote>
<p><code>styled-components</code> 同时支持为组件传入 <code>html</code> 元素的其他属性，比如为 <code>input</code> 元素指定一个 <code>type</code> 属性，我们可以使用 <code>attrs</code> 方法来完成</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> Password = styled.input.attrs(&#123;</span><br><span class="line">  type: <span class="string">'password'</span>,</span><br><span class="line">&#125;)<span class="string">`</span></span><br><span class="line"><span class="string">  color: palevioletred;</span></span><br><span class="line"><span class="string">  font-size: 1em;</span></span><br><span class="line"><span class="string">  border: 2px solid palevioletred;</span></span><br><span class="line"><span class="string">  border-radius: 3px;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>在实际开发中，这个方法还有一个有用处，用来引用第三方类库的 <code>css</code>样式：</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> Button = styled.button.attrs(&#123;</span><br><span class="line">  className: <span class="string">'small'</span>,</span><br><span class="line">&#125;)<span class="string">`</span></span><br><span class="line"><span class="string">  background: black;</span></span><br><span class="line"><span class="string">  color: white;</span></span><br><span class="line"><span class="string">  cursor: pointer;</span></span><br><span class="line"><span class="string">  margin: 1em;</span></span><br><span class="line"><span class="string">  padding: 0.25em 1em;</span></span><br><span class="line"><span class="string">  border: 2px solid black;</span></span><br><span class="line"><span class="string">  border-radius: 3px;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>编译后的 <code>html</code> 结构如下：</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;button <span class="class"><span class="keyword">class</span></span>=<span class="string">"sc-gPEVay small gYllyG"</span>&gt;</span><br><span class="line">  Styled Components</span><br><span class="line">&lt;<span class="regexp">/button&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>可以用这种方式来使用在别处定义的 <code>small</code> 样式，或者单纯为了识别自己定义的 <code>class</code>，因为正常情况下我们得到的 <code>class</code>名是不可读的编码</p>
</blockquote>
<h2 id="六、CSS-动画支持"><a href="#六、CSS-动画支持" class="headerlink" title="六、CSS 动画支持"></a>六、CSS 动画支持</h2><ul>
<li><code>styled-components</code> 同样对 <code>css</code> 动画中的 <code>@keyframe</code> 做了很好的支持。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; keyframes &#125; <span class="keyword">from</span> <span class="string">'styled-components'</span>;</span><br><span class="line"><span class="keyword">const</span> fadeIn = keyframes<span class="string">`</span></span><br><span class="line"><span class="string">  0% &#123;</span></span><br><span class="line"><span class="string">    opacity: 0;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  100% &#123;</span></span><br><span class="line"><span class="string">    opacity: 1;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> FadeInButton = styled.button<span class="string">`</span></span><br><span class="line"><span class="string">  animation: 1s <span class="subst">$&#123;fadeIn&#125;</span> ease-out;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>
<h2 id="七、兼容现在已有的-react-components-和-css-框架"><a href="#七、兼容现在已有的-react-components-和-css-框架" class="headerlink" title="七、兼容现在已有的 react components 和 css 框架"></a>七、兼容现在已有的 react components 和 css 框架</h2><blockquote>
<p><code>styled-components</code> 采用的 <code>css-module</code> 的模式有另外一个好处就是可以很好的与其他的主题库进行兼容。因为大部分的 <code>css</code> 框架或者<code>css</code>主题都是以 <code>className</code> 的方式进行样式处理的，额外的 <code>className</code> 和主题的 <code>className</code> 并不会有太大的冲突</p>
</blockquote>
<ul>
<li><code>styled-components</code> 的语法同样支持对一个 <code>React</code>组件进行扩展</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> StyledDiv = styled(Row)<span class="string">`</span></span><br><span class="line"><span class="string">  position: relative;</span></span><br><span class="line"><span class="string">  height: 100%;</span></span><br><span class="line"><span class="string">  .image img &#123;</span></span><br><span class="line"><span class="string">    width: 100%;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  .content &#123;</span></span><br><span class="line"><span class="string">    min-height: 30em;</span></span><br><span class="line"><span class="string">    overflow: auto;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">  .content h2 &#123;</span></span><br><span class="line"><span class="string">    font-size: 1.8em;</span></span><br><span class="line"><span class="string">    color: black;</span></span><br><span class="line"><span class="string">    margin-bottom: 1em;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>
<h2 id="八、实战篇"><a href="#八、实战篇" class="headerlink" title="八、实战篇"></a>八、实战篇</h2><p><strong>extend与styled</strong></p>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line"><span class="comment">/*基础组件button*/</span></span><br><span class="line">export const Button = styled.button`</span><br><span class="line">    <span class="selector-tag">border-radius</span>: 3<span class="selector-tag">px</span>;</span><br><span class="line">    <span class="selector-tag">padding</span>: 0<span class="selector-class">.25em</span> 1<span class="selector-tag">em</span>;</span><br><span class="line">    <span class="selector-tag">margin</span>: 0 1<span class="selector-tag">em</span>;</span><br><span class="line">    background: $&#123;props=&gt;props.primary?"palevioletred":"transparent"&#125;;</span><br><span class="line">    color: $&#123;props=&gt;props.primary?"white":"palevioletred"&#125;;</span><br><span class="line">    <span class="selector-tag">border</span>: 2<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-tag">palevioletred</span>;</span><br><span class="line">`;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*扩展按钮的属性，不再原来基础上修改 如在&lt;button class="abc con"&gt;上添加一个con类一样*/</span></span><br><span class="line">export const AButton = styled(Button)`</span><br><span class="line">    <span class="selector-tag">width</span><span class="selector-pseudo">:200px</span>;</span><br><span class="line">    <span class="selector-tag">height</span><span class="selector-pseudo">:20px</span>;</span><br><span class="line">    <span class="selector-tag">padding</span><span class="selector-pseudo">:20px</span>;</span><br><span class="line">`</span><br><span class="line"></span><br><span class="line"><span class="comment">/*扩展的结果*/</span></span><br><span class="line"><span class="selector-tag">button</span> &#123;</span><br><span class="line">    <span class="attribute">border-radius</span>: <span class="number">3px</span>;</span><br><span class="line">    <span class="attribute">padding</span>: <span class="number">0.25em</span> <span class="number">1em</span>;</span><br><span class="line">    <span class="attribute">margin</span>: <span class="number">0</span> <span class="number">1em</span>;</span><br><span class="line">    <span class="attribute">background</span>: transparent;</span><br><span class="line">    <span class="attribute">color</span>: palevioletred;</span><br><span class="line">    <span class="attribute">border</span>: <span class="number">2px</span> solid palevioletred;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**添加的扩展属性**/</span></span><br><span class="line"><span class="selector-class">.con</span> &#123;</span><br><span class="line">    <span class="attribute">background</span>: yellow;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/*继承按钮的样式并且在原来基础上修改  如在&lt;button class="con"&gt;.con类上叠加属性一样**/</span></span><br><span class="line">export const TomatoButton = Button.extend`</span><br><span class="line">    <span class="selector-tag">width</span><span class="selector-pseudo">:200px</span>;</span><br><span class="line">    <span class="selector-tag">height</span><span class="selector-pseudo">:10</span>%;</span><br><span class="line">`</span><br><span class="line"><span class="comment">/*继承的结果  子组件中的属性会覆盖父组件中同名的属性*/</span></span><br><span class="line"><span class="selector-tag">button</span> &#123;</span><br><span class="line">    <span class="attribute">border-radius</span>: <span class="number">3px</span>;</span><br><span class="line">    <span class="attribute">padding</span>: <span class="number">0.25em</span> <span class="number">1em</span>;</span><br><span class="line">    <span class="attribute">margin</span>: <span class="number">0</span> <span class="number">1em</span>;</span><br><span class="line">    <span class="attribute">background</span>: transparent;</span><br><span class="line">    <span class="attribute">color</span>: palevioletred;</span><br><span class="line">    <span class="attribute">border</span>: <span class="number">2px</span> solid palevioletred;</span><br><span class="line">    <span class="comment">/*添加的继承属性*/</span></span><br><span class="line">    <span class="attribute">width</span>: <span class="number">200px</span>;</span><br><span class="line">    <span class="attribute">height</span>: <span class="number">10%</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line">const Button = styled.button`</span><br><span class="line">  <span class="selector-tag">padding</span>: 10<span class="selector-tag">px</span>;</span><br><span class="line">`;</span><br><span class="line">const TomatoButton = Button.extend`</span><br><span class="line">  <span class="selector-tag">color</span>: <span class="selector-id">#f00</span>;</span><br><span class="line">`;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** css写法 **/</span></span><br><span class="line"><span class="selector-tag">button</span> &#123;</span><br><span class="line">  <span class="attribute">padding</span>: <span class="number">10px</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">button</span><span class="selector-class">.tomato-button</span> &#123;</span><br><span class="line">  <span class="attribute">color</span>: <span class="number">#f00</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>传递属性的两中写法</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Button</span> <span class="attr">primary</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">Button</span> <span class="attr">secondary</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">Button</span> <span class="attr">primary</span> <span class="attr">active</span>=<span class="string">&#123;true&#125;</span> /&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line"><span class="comment">/*对单个属性的值做判断赋值*/</span></span><br><span class="line"><span class="selector-tag">styled</span><span class="selector-class">.Button</span>`</span><br><span class="line">  background: $&#123;props =&gt; props.primary ? '#f00' : props.secondary ? '#0f0' : '#00f'&#125;;</span><br><span class="line">  color: $&#123;props =&gt; props.primary ? '#fff' : props.secondary ? '#fff' : '#000'&#125;;</span><br><span class="line">  opacity: $&#123;props =&gt; props.active ? 1 : 0&#125;;</span><br><span class="line">`;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">const Button = styled.button`</span><br><span class="line">	<span class="selector-tag">border-radius</span>: 3<span class="selector-tag">px</span>;</span><br><span class="line">	<span class="selector-tag">padding</span>: 0<span class="selector-class">.25em</span> 1<span class="selector-tag">em</span>;</span><br><span class="line">	<span class="selector-tag">margin</span>: 0 1<span class="selector-tag">em</span>;</span><br><span class="line">	<span class="selector-tag">background</span>: <span class="selector-tag">transparent</span>;</span><br><span class="line">	<span class="selector-tag">color</span>: <span class="selector-tag">palevioletred</span>;</span><br><span class="line">	<span class="selector-tag">border</span>: 2<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-tag">palevioletred</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*可以写一堆属性*/</span></span><br><span class="line">	$&#123;props =&gt; props.primary &amp;&amp; css`</span><br><span class="line">		<span class="selector-tag">background</span>: <span class="selector-tag">palevioletred</span>;</span><br><span class="line">		<span class="selector-tag">color</span>: <span class="selector-tag">white</span>;</span><br><span class="line">	`&#125;</span><br><span class="line">`;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**css写法**/</span></span><br><span class="line"><span class="selector-tag">button</span> &#123;</span><br><span class="line">  <span class="attribute">background</span>: <span class="number">#00f</span>;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">0</span>;</span><br><span class="line">  <span class="attribute">color</span>: <span class="number">#000</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">button</span><span class="selector-class">.primary</span>,</span><br><span class="line"><span class="selector-tag">button</span><span class="selector-class">.seconary</span> &#123;</span><br><span class="line">  <span class="attribute">color</span>: <span class="number">#fff</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">button</span><span class="selector-class">.primary</span> &#123;</span><br><span class="line">  <span class="attribute">background</span>: <span class="number">#f00</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">button</span><span class="selector-class">.secondary</span> &#123;</span><br><span class="line">  <span class="attribute">background</span>: <span class="number">#0f0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">button</span><span class="selector-class">.active</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>使用</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Button</span> <span class="attr">primary</span>&gt;</span><span class="tag">&lt;/<span class="name">Button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="九、总结"><a href="#九、总结" class="headerlink" title="九、总结"></a>九、总结</h2><ul>
<li>提出了 <code>container</code> 和 <code>components</code> 的概念，移除了组件和样式之间的映射关系，符合关注度分离的模式；</li>
<li>可以在样式定义中直接引用到 <code>js</code> 变量，共享变量，非常便利；</li>
<li>支持组件之间继承，方便代码复用，提升可维护性；</li>
<li>兼容现有的 <code>className</code> 方式，升级无痛；</li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2017/11/07/es-in-react/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2017/11/08/axios/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
